<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('科目管理') }}</span>
    </div>
    <el-radio-group v-model="subjectType" size="small" class="subjectCode mb15">
      <el-radio-button v-for="dict in subjectTypeOptions" :key="dict.dictValue" :label="dict.dictValue" @click.native.prevent="radioChange(dict.dictValue)">{{ $t(dict.dictLabel) }}</el-radio-button>
    </el-radio-group>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['fin:subjectManage:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t('新增') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['fin:subjectManage:import']"
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="uploadHandle"
        >{{ $t('导入') }}</el-button>
      </el-col>
    </el-row>
    <div>
      <el-table ref="table" v-loading="loading" :data="finSubjectManageList" tooltip-effect="darkTable" row-key="id" border default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column :label="$t('科目编码')" prop="subjectCode" show-overflow-tooltip min-width="180" />
        <el-table-column :label="$t('科目名称')" prop="subjectName" show-overflow-tooltip />
        <el-table-column :label="$t('科目类别')" align="center" prop="subjectType" :formatter="subjectTypeFormat" />
        <el-table-column :label="$t('余额方向')" align="center" prop="balanceDirection" :formatter="balanceDirectionFormat" />
        <el-table-column :label="$t('排序')" align="center" prop="sort" />
        <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="280">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['fin:subjectManage:edit']"
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="updateHandle(scope.row)"
            >{{ $t('修改') }}
            </el-button>
            <el-button
              v-hasPermi="['fin:subjectManage:edit']"
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="createNextLevel(scope.row)"
            >{{ $t('新增下一级') }}
            </el-button>
            <el-button
              v-hasPermi="['fin:subjectManage:remove']"
              size="small"
              type="text"
              icon="el-icon-delete"
              @click="deleteHandle(scope.row)"
            >{{ $t('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加或修改财务核心-科目管理对话框 -->
    <el-dialog :title="$t(title)" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <finSubjectManageForm ref="finSubjectManageForm" />
    </el-dialog>

    <el-dialog
      title="Excel上传"
      :visible.sync="upload.open"
      width="400px"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <div v-loading="upload.loading">
        <el-upload
          ref="upload"
          class="upload-demo"
          drag
          :headers="upload.headers"
          :action="upload.url"
          :show-file-list="true"
          :disabled="upload.loading"
          :multiple="upload.multiple"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-exceed="handleFileExceed"
          :auto-upload="false"
          :file-list="upload.fileList"
          :accept="upload.accept"
          :before-upload="beforeUpload"
          style="color: #1890ff;"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            {{ $t('将文件拖到此处，或点击') }}
            <em>{{ $t('上传') }}</em>
            <p class="tip_phrase">仅允许导入"xls,xlsx"文件</p>
          </div>
          <div slot="tip" class="el-upload__tip">
            <el-link :underline="false" type="primary" style="font-size:14px;margin-top:10px" @click="fetchTemplate">
              {{ $t('下载Excel模板') }}
            </el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer" style="text-align: right;">
          <el-button size="small" @click="upload.open = false">{{ $t('取消') }}</el-button>
          <el-button size="small" type="primary" @click="submitFileForm">{{ $t('上传') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  delFinSubjectManage,
  exportFinSubjectManage,
  getSubjectTreeData
} from '@/api/fin/subjectManage/finSubjectManage'
import finSubjectManageForm from './finSubjectManageForm.vue'
import { getToken } from '@/utils/auth'
export default {
    components: {
        finSubjectManageForm
    },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 财务核心-科目管理表格数据
          finSubjectManageList: [],
          // 弹出层标题
          title: '科目管理',
          // 是否显示弹出层
          formOpen: false,
          // 科目类别字典
          subjectTypeOptions: [],
          // 余额方向字典
          balanceDirectionOptions: [],
          finSubjectManageCacheList: [],
          upload: {
            open: false,
            loading: false,
            fileList: [],
            // 弹出层标题（项目导入）
            title: '',
            // 是否禁用上传
            isUploading: false,
            // 设置上传的请求头部
            headers: { Authorization: 'Bearer ' + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + '/subjectManage/finSubjectManage/importData',
            accept: '.xls, .xlsx',
            multiple: false
          },
          subjectType: ''
      }
  },
  created() {
      this.getList()
      this.getDicts('subject_category').then(response => {
          this.subjectTypeOptions = response.data
      })
      this.getDicts('balance_direction').then(response => {
          this.balanceDirectionOptions = response.data
      })
  },
  methods: {
    /** 查询财务核心-科目管理列表 */
    getList() {
        this.loading = true
        getSubjectTreeData(this.queryParams).then(response => {
            this.finSubjectManageList = response.data || []
            this.finSubjectManageCacheList = JSON.parse(JSON.stringify(this.finSubjectManageList))
            this.loading = false
        }).catch(() => {
            this.loading = false
        })
    },
    // 科目类别字典翻译
    subjectTypeFormat(row) {
      return this.selectDictLabel(this.subjectTypeOptions, row.subjectType)
    },
    // 余额方向字典翻译
    balanceDirectionFormat(row) {
      return this.selectDictLabel(this.balanceDirectionOptions, row.balanceDirection)
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.$nextTick(() => {
            this.$refs.finSubjectManageForm.init(null)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.finSubjectManageForm.init(row)
        })
    },
    createNextLevel(row) {
      this.formOpen = true
      this.$nextTick(() => {
        this.$refs.finSubjectManageForm.nextInit(row)
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(() => {
            return delFinSubjectManage(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(() => {
            this.loading = false
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
        const queryParams = this.queryParams
        this.$confirm(this.$t('是否确认导出数据项?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(() => {
            return exportFinSubjectManage(queryParams)
        }).then(response => {
            this.download(response.msg)
        }).catch(() => {
        })
    },
    radioChange(e) {
      if (this.subjectType === e) {
        this.subjectType = ''
        this.finSubjectManageList = this.finSubjectManageCacheList
      } else {
        this.subjectType = e
        this.finSubjectManageList = this.filterTree(this.finSubjectManageCacheList, e, true)
      }
    },
    filterTree(arr, keyword, first = true) {
      if (first) {
        arr = JSON.parse(JSON.stringify(arr))
      }
      const emptyArr = []
      for (const item of arr) {
        if (item.subjectType.includes(keyword)) {
          if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            item.children = this.filterTree(item.children, keyword, false)
          }
          emptyArr.push(item)
        } else if (item.children && Array.isArray(item.children) && item.children.length > 0) {
          item.children = this.filterTree(item.children, keyword, false)
          if (item.children.length) {
            emptyArr.push(item)
          }
        }
      }
      return emptyArr
    },
    uploadHandle() {
      this.upload.open = true
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      window.location.href = url + '/template/科目导入模板.xlsx'
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.loading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.upload.loading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 文件达到上限处理
    handleFileExceed() {
      this.msgError(this.$t('最多可上传1个文件'))
    },
    beforeUpload(file) {
      const fileType = file.type
      console.log('fileType', fileType)
      return true
    },
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/.subjectCode{
  .el-radio-button__inner{
    font-size: 12px!important;
    padding: 6px 20px !important;
    border-radius: 8px;
    background: #F4F4F4;
    border: 1px solid #F4F4F4;
    color: #898989;
    outline: none!important;
    outline-color: transparent!important;
    transition: unset!important;
    box-shadow: unset!important;
    border-left: 1px solid #F4F4F4;
  }
  .el-radio-button__orig-radio:checked+.el-radio-button__inner {
    font-size: 12px!important;
    background: rgba(24,144,255, 0.08);
    border: 1px solid #1890ff;
    color: #1890ff;
    position: relative;
    overflow: hidden;
    &::before{
      position: absolute;
      content: "";
      display: block;
      bottom: 2px;
      right: 2px;
      width: 4px;
      height: 7px;
      border-style: solid;
      border-color: #fff;
      border-width: 0 2px 2px 0;
      transform: rotate(45deg);
      z-index: 1;
    }
    &::after{
      position: absolute;
      content: "";
      display: block;
      bottom: -9px;
      right: -9px;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: #1890ff;
      z-index: 0;
    }
  }
  .el-radio-button:focus:not(.is-focus):not(:active):not(.is-disabled) {
    box-shadow: unset!important;
}
  .el-radio-button {
    margin-right: 10px;
    margin-bottom: 3px;
  }

}
</style>
